package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.service.MailServcie;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by emily
 * 电子邮件服务
 */
@Slf4j
@Service("mailServcie")
public class MailServcieImpl implements MailServcie{

    //logger日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //邮件发送人，自己的邮箱地址
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;


    @Override
    public JSONObject sendSimpleMail(String toUserMail, String subject, String content) {
        JSONObject result = new JSONObject();

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        try {
            //发送给谁
            mailMessage.setTo(toUserMail);
            mailMessage.setSubject(subject);
            mailMessage.setText(content);
            //邮件发送人
            mailMessage.setFrom(from);
            //通过JavaMailSender 将邮件发送出去
            mailSender.send(mailMessage);

            logger.info("----------------------邮件发送成功:"+dateFormat.format(new Date()));
            result.put("status", 0);
            result.put("msg", "ok");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----------------------邮件发送失败：",dateFormat.format(new Date()),e);
            result.put("status", 40002);
            result.put("msg", e);
        }
        System.out.println("sendSimpleMail："+result.toString());
        return result;
    }

    @Override
    public JSONObject sendHtmlMail(String toUserMail, String subject, String content) {

        JSONObject result = new JSONObject();
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

            helper.setTo(toUserMail);
            helper.setSubject(subject);
            //true：支持HTML发送邮件
            helper.setText(content,true);
            helper.setFrom(from);
            mailSender.send(mimeMessage);
            logger.info("----------------------邮件发送成功:"+dateFormat.format(new Date()));

            result.put("status", 0);
            result.put("msg", "ok");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("----------------------邮件发送失败：",dateFormat.format(new Date()),e);
            result.put("status", 40002);
            result.put("msg", e);
        }
        System.out.println("sendHtmlMail："+result.toString());
        return result;
    }

    @Override
    public JSONObject sendAttachmentsMail(String toUserMail, String subject, String content, String filePath) {
        JSONObject result = new JSONObject();

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setTo(toUserMail);
            helper.setSubject(subject);
            helper.setText(content,true);
            helper.setFrom(from);

            FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
            //获取文件名
            String pathName = fileSystemResource.getFilename();
            helper.addAttachment(pathName,fileSystemResource);
            helper.addAttachment(pathName+"_test",fileSystemResource); //同时发送多个附件
            mailSender.send(mimeMessage);

            logger.info("----------------------邮件发送成功:"+dateFormat.format(new Date()));
            result.put("status", 0);
            result.put("msg", "ok");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("----------------------邮件发送失败：",dateFormat.format(new Date()),e);
            result.put("status", 40002);
            result.put("msg", e);
        }
        System.out.println("sendAttachmentsMail："+result.toString());
        return result;
    }

    @Override
    public JSONObject sendInlineResoureMail(String toUserMail, String subject, String content,
                                      String rscPath, String rscId) {
        JSONObject result = new JSONObject();
        logger.info("发送带图片的HTML邮件开始：{},{},{},{},{}",toUserMail,subject,content,rscPath,rscId);
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

            helper.setFrom(from);
            helper.setTo(toUserMail);
            helper.setSubject(subject);
            helper.setText(content,true);

            //获取上传的文件路径
            FileSystemResource fileSystemResource = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId,fileSystemResource);
            helper.addInline(rscId,fileSystemResource);
            mailSender.send(mimeMessage);

            logger.info("----------------------邮件发送成功:"+dateFormat.format(new Date()));

            result.put("status", 0);
            result.put("msg", "ok");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("----------------------邮件发送失败：",dateFormat.format(new Date()),e);
            result.put("status", 40002);
            result.put("msg", e);
            logger.error("发送带图片的HTML邮件失败：",e);
        }
        System.out.println("sendInlineResoureMail："+result.toString());
        return result;
    }
}
